export default function useAsyncFn(fn) {
  const lastId = useRef(0);
  const [state, setState] = useState({
    loading: false
  })
  const isMounted = useMountedStatus();
  const handle = useCallBack((...arg) => {
    const id = ++lastId.current
    return fn(...arg).then(res => {
      if (isMounted() && id === lastId.current) {
        setState({
          loading: false,
          value: res
        })
      }
      return res
    }, err => {
      if (isMounted() && id === lastId.current) {
        setState({
          loading: false,
          error: err
        })
      }
      return err
    })

  }, [fn])
  return [state, handle]
}